<template>
    <div class="barwrap">
        <van-cell :title="_title" icon="chart-trending-o" />
        <div :id="props.id" 
        style="width: 100%;height: 200px;"
        ></div>
    </div>
</template>

<script setup>
import * as echarts from 'echarts';
import {
    defineExpose,
    defineProps,
    ref
} from "vue";

const _title = ref('');

const props = defineProps({
    id: {
        type: String,
        default: 'main',
    }
});

const updateValue = (params) => {
    console.log('params=======>', JSON.stringify(params))
    const { rawData, seriesData, xAxisData, title } = params;
    
    _title.value = title;
    var chartDom = document.getElementById(props.id);
    var myChart = echarts.init(chartDom);
    let option;

    // There should not be negative values in rawData
    const totalData = [];
    for (let i = 0; i < rawData[0].length; ++i) {
        let sum = 0;
        for (let j = 0; j < rawData.length; ++j) {
            sum += rawData[j][i];
        }
        totalData.push(sum);
    }
    const grid = {
        left: 40,
        right: 20,
        top: 30,
        bottom: 40
    };
    const series = seriesData.map((name, sid) => {
        return {
            name,
            type: 'bar',
            stack: 'total',
            barWidth: '70%',
            label: {
                show: true,
                formatter: (params) => {
                    const { seriesName,  dataIndex } = params;
                    if (seriesName == name) {
                        return rawData[sid][dataIndex];
                    }
                    // Math.round(params.value * 1000) / 10 + '%'
                } 
            },
            data: rawData[sid].map((d, did) =>
                totalData[did] <= 0 ? 0 : d / totalData[did]
            )
        };
    });
    option = {
        title: {
            // left: 'center',
            // text: title
        },
        legend: {
            type: 'scroll',
            selectedMode: false
        },
        grid,
        yAxis: {
            type: 'value'
        },
        xAxis: {
            type: 'category',
            data: xAxisData,
            axisLabel: {
                interval: 0, // 显示所有标签
                rotate: 45,
                fontSize: 10
            }
        },
        series
    };

    option && myChart.setOption(option);

}

defineExpose({ updateValue })



</script>

<style lang="scss" scoped>
.barwrap {
    width: 100%;
    display: flex;
    flex-direction: column;

    .title {
        font-size: 16px;
        color: #666;
        font-weight: 400;
        padding: 10px 0;
    }
}
</style>